﻿$(function () {
    ue = UE.getEditor('ueditor', {
        serverUrl: '/UEditor/controller.asp',
        toolbars: [
            ["fontsize", "forecolor", "backcolor", "bold", "italic", "underline", "|", "justifyleft", "justifycenter", "justifyright", "indent", "|", "insertorderedlist", "insertunorderedlist", "|", "simpleupload", "link", "unlink", "|", "redo", "undo"]
        ],
        initialFrameHeight: 200,
        pasteplain: true,
        enableContextMenu: false,
        elementPathEnabled: false,
        autosave: true,
        wordCount: false
    });

    layui.use(['upload', 'element', 'layer', 'laydate'], function () {
        var $ = layui.jquery
            , upload = layui.upload
            , element = layui.element
            , layer = layui.layer
            , laydate = layui.laydate;
        //多图片上传
        upload.render({
            elem: '.image-selector'
            , url: '/Files/Upload.aspx' //此处配置你自己的上传接口即可
            , multiple: true
            , auto: false
            , choose: function (obj) {
                var that = this;
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    const isFirst = Object.keys(files).length === 1;
                    let itemNode = $([
                        `<div class="layui-col-sm2 layui-col-md2" id="preview-item-${index}">` +
                        `<div class="preview-item ${isFirst ? 'cover' : ''}">` +
                        `<img class="handle" id="preview-img-${index}" style="display: none;" />` +
                        `<div class="layui-progress" id="preview-progress-${index}" lay-filter="preview-progress-${index}">` +
                        '<div class="layui-progress-bar" lay-percent=""></div>' +
                        '</div>' +
                        '<div class="remove">' +
                        '<i class="layui-icon layui-icon-close"></i>' +
                        '</div>' +
                        '</div>' +
                        '</div>'
                    ].join(''));

                    itemNode.find('.remove').on('click', function () {
                        layer.confirm('是否确定删除图片？', {
                            btn: ['确定', '取消'] //按钮
                        }, function (confirmIndex) {
                            delete files[index];
                            $(`#preview-item-${index}`).remove()
                            layer.close(confirmIndex);
                        }, function () {

                        });
                    })
                    $('#preview-list').append(itemNode)
                    element.render('progress');
                    obj.upload(index, file);
                });
            }
            , done: function (res, index) {
                //上传完毕
                $(`#preview-progress-${index}`).hide();
                $(`#preview-img-${index}`).show().attr('src', res.url)

            }, progress: function (n, elem, e, index) { //注意：index 参数为 layui 2.6.6 新增
                element.progress('preview-progress-' + index, n + '%');

            }
        });

        //日期
        laydate.render({
            elem: '#endTime'
            , min: +1
            , theme: '#b15a73'
            , value: deadline
        });

    })

    //类型标签
    layui.config({
        base: '/Content/Scripts/'
    }).use(['inputTag'], function () {
        var inputTag = layui.inputTag;
        typeTag = inputTag.render({
            elem: '.typeTag',
            data: [...typeTagData],//初始值
            permanentData: [],//不允许删除的值
            removeKeyNum: 8,//删除按键编号 默认，BackSpace 键
            createKeyNum: 13,//创建按键编号 默认，Enter 键
            theme: "fairy-bg-info",
            beforeCreate: function (data, value) {//添加前操作，必须返回字符串才有效
                if (data.length < 3) {
                    return value;
                }
            },
            onChange: function (data, value, type) {
            }
        });

        $("#typeTag_id").find('.fairy-tag').on('click', function () {
            let value = this.innerText;
            typeTag.createItem(value)
        })
    })

    //风格标签
    layui.config({
        base: '/Content/Scripts/'
    }).use(['inputTag'], function () {
        var inputTag = layui.inputTag;
        styleTag = inputTag.render({
            elem: '.styleTag',
            data: [...styleTagData],//初始值
            permanentData: [],//不允许删除的值
            removeKeyNum: 8,//删除按键编号 默认，BackSpace 键
            createKeyNum: 13,//创建按键编号 默认，Enter 键
            theme: "fairy-bg-info",
            beforeCreate: function (data, value) {//添加前操作，必须返回字符串才有效
                if (data.length < 3) {
                    return value;
                }
            },
            onChange: function (data, value, type) {
            }
        });

        $("#styleTag_id").find('.fairy-tag').on('click', function () {
            let value = this.innerText;
            styleTag.createItem(value)
        })
    })


    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        //自定义验证规则
        form.verify({
            priceMin: function (value) {
                if (value < 50) {
                    return '预算不能低于50';
                }
            },
            priceMax: function (value) {
                if (value < 50) {
                    return '预算不能低于50';
                }

                let priceMin = $('input[name="priceMin"]').val()
                if (parseInt(value) < parseInt(priceMin)) {
                    return '最小预算不能大于最大预算';
                }
            },
            editorValue: function (value) {
                if (value.length < 1) {
                    return '请输入需求详情';
                }
            }
        });

        //监听提交
        form.on('submit(form)', function (data) {
            data = data.field;
            delete data.editorValue;
            let content = ue.getContent()
            if (content.length < 1) {
                layer.msg('请输入需求详情', { icon: 5, anim: 6 });
                return false;

            }
            let tag = [...typeTag.options.data, "@", ...styleTag.options.data];

            const mode = utils.getQueryVariable("mode");

            const postData = Object.assign({}, data, {
                action: mode ? "Update" : "Insert",
                tag: JSON.stringify(tag),
                content,
            });

            postData.ProjectID = utils.getQueryVariable("id");


            $.ajax({
                url: "/Project/Handle.aspx",
                data: postData,
                method: "post",
                success: (res) => {
                    layer.alert(res.msg, () => {
                        location.href = "/Project/Detail.aspx?id=" + res.data.id;
                    })
                }
            })

        });

    })
})

$(function () {
    const typeTagNodes = tagOptions.types.map(item => `<span class="fairy-tag fairy-anim-fadein pointer">${item}</span>`).join("");
    $("#typeTag_id").append(typeTagNodes)

    const styleTagNodes = tagOptions.styles.map(item => `<span class="fairy-tag fairy-anim-fadein pointer">${item}</span>`).join("");
    $("#styleTag_id").append(styleTagNodes)

})